package main.java.com.itlin.datastructure.linkedlist;

import java.util.Iterator;
import java.util.function.Consumer;

public class DoublyCircleLinkedListSentinel implements Iterable<Integer> {//整体

    //head 哨兵
    private Node sentinel = new Node(null,-1,null);//哨兵节点



    //节点类
    private static class Node {

        Node pre;//上一个节点指针
        int value; //值
        Node next;//下一个节点指针

        public Node(Node pre,int value ,Node next){
            this.pre = pre;
            this.value = value;
            this.next = next;
        }
    }

    public DoublyCircleLinkedListSentinel(){
        sentinel.next = sentinel;
        sentinel.pre = sentinel;
    }
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node pointer = sentinel.next;
            @Override
            public boolean hasNext() {//询问是否有下一个元素
                return pointer != sentinel;
            }

            @Override
            public Integer next() {//返回当前元素的值，并且指向下一个元素
                int value = pointer.value;
                pointer = pointer.next;
                return value;
            }
        };
    }





    public void addFirst(int value) {

        Node pre = sentinel;
        Node next = sentinel.next;
        Node added = new Node(pre,value,next);
        pre.next = added;
        next.pre = added;
    }





    public void addLast(int value){

        Node last = sentinel;
        Node previous = sentinel.pre;
        Node added = new Node(previous, value, last);
        previous.next = added;
        last.pre = added;


    }








    private static IllegalArgumentException illegalIndex(int index) {
        return new IllegalArgumentException(String.format("index[%d] 不合法%n", index));
    }



    public void removeFirst(){

        Node previous = sentinel;
        Node removed = sentinel.next;
        if (removed == sentinel){
            throw new IllegalArgumentException("非法操作");
        }
        Node next = removed.next;

        previous.next = next;
        next.pre = previous;

    }

    /**
     * 删除最后节点
     */
    public void removeLast(){

        Node removed = sentinel.pre;
        if (removed == sentinel){
            throw new IllegalArgumentException("非法操作");
        }
        Node last = sentinel;
        Node previous = removed.pre;

        previous.next = last;
        last.pre = previous;
    }



    private Node findByValue(int value){
        Node pointer = sentinel.next;
        while(pointer != sentinel){
            if (pointer.value == value){
                return pointer;
            }
            pointer = pointer.next;
        }
        return null;
    }

    public void removeByValue(int value){
        Node removed = findByValue(value);
        if (removed == null){
            return;//不用删除
        }
        Node previous = removed.pre;
        Node next = removed.next;
        previous.next = next;
        next.pre = previous;
    }



}


